package com.cooper.controllers;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.cooper.constants.AppConstants;
import com.cooper.core.JsonResult;
import com.cooper.domain.UserSession;
import com.cooper.entity.UserInfo;
import com.cooper.security.PasswordGeneration;
import com.cooper.service.core.UserService;
import com.cooper.util.Controllers;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.Param;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;

public class LoginController {
	
	public static final String ORIGIN_URL = "originURL";
	
	@Autowired
	private UserService userService;
	
	@Get
	public String show(Invocation inv) throws Exception{
		inv.addModel(ORIGIN_URL, inv.getParameter(ORIGIN_URL));
		inv.addModel("usePanel", inv.getParameter("usePanel"));
		return "login";
	}
	
	@Post
	public Object login(Invocation inv, @Param("userName") String userName,
			@Param("userPassword") String userPassword) throws Exception{
		JsonResult json = new JsonResult();
		if(null == userName || null == userPassword){
			json.setMessage("请输入用户名密码!");
			return json;
		}
		UserInfo user = new UserInfo();
		user.setUserName(userName);
		try{
			user.setUserPassword(PasswordGeneration.encrypt(userPassword));
		} catch(Exception e){
			json.setMessage("密码加密时出现错误.");
			e.printStackTrace();
			return json;
		}
		UserInfo userInfo = this.userService.checkPassword(user);
		if (null == userInfo) {
			json.setMessage("用户名或密码错误!");
			return json;
		}
		
		UserSession userSession = new UserSession();
		userSession.setUserInfo(userInfo);
		userSession.setDesignerPhoto(userInfo.getUserFileId());;
		
		HttpServletRequest request = inv.getRequest();
		//获取真实的IP地址
		String ip = request.getHeader("X-Real-IP");
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	        ip = request.getRemoteAddr();
	    }
	    
	    Controllers.prepareEntityForDataSaving(userInfo, userInfo, true);
		this.userService.logUserLogin(userInfo, ip, request.getSession().getId());
		request.getSession().setAttribute(AppConstants.USER_SESSION_NAME, userSession);
		
		json.setSuccess(true);
		String originURL = inv.getParameter(ORIGIN_URL);
		if(StringUtils.isEmpty(originURL)){
			originURL = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
		}
		json.setMessage(originURL);
		return json;
	}
}
